import { useIntersectionObserver } from '@vueuse/core'
import load from '@/assets/loading.gif'
export default {
  install(app) {
    app.directive('imglazy', {
      mounted(imgDom, binding) {
        const { stop } = useIntersectionObserver(
          imgDom,
          ([{ isIntersecting }]) => {
            if (isIntersecting) {
              imgDom.src = load
              setTimeout(() => {
                imgDom.src = binding.value
              }, 300)
              // 图片加载错误
              imgDom.onerror = () => {
                imgDom.src = load
              }
              stop() // 进入可视区后停止监控，以免重复调用
            }
          },
          {
            // 阈值
            threshold: 0
          }
        )
      }
    })
  }
}
